package com.ilink.groundservice.service.impl.study;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.groundservice.entity.PO.study.practice.StudyPractice;
import com.ilink.groundservice.entity.PO.study.practice.StudyPracticeBook;
import com.ilink.groundservice.mapper.study.practice.StudyPracticeBookMapper;
import com.ilink.groundservice.mapper.study.practice.StudyPracticeMapper;
import com.ilink.groundservice.service.study.StudyPracticeService;
import com.ilink.ilinkcommon.service.oss.OssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class StudyPracticeServiceImpl implements StudyPracticeService {
    private final StudyPracticeMapper studyPracticeMapper;
    private final StudyPracticeBookMapper studyPracticeBookMapper;
    private final OssService ossService;

    @Override
    public List<String> getAllPracticeTags() {
        // 查询并去重
        return studyPracticeMapper.selectList(new QueryWrapper<>()).stream()
            .map(StudyPractice::getPracticeTag)
            .distinct()
            .collect(Collectors.toList());
    }


    @Override
    public IPage<StudyPractice> getPracticeByCondition(String keywords, String tag, int page, int size) {
        LambdaQueryWrapper<StudyPractice> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(keywords)) {
            queryWrapper.like(StudyPractice::getPracticeName, keywords)
                .or()
                .like(StudyPractice::getPracticeIntroduction, keywords);
        }
        if (StringUtils.isNotBlank(tag)) {
            queryWrapper.eq(StudyPractice::getPracticeTag, tag);
        }

        // 创建分页对象
        Page<StudyPractice> practicePage = new Page<>(page, size);
        IPage<StudyPractice> resultPage = studyPracticeMapper.selectPage(practicePage, queryWrapper);

        // 更新每个实例的 practiceImage 字段
        resultPage.getRecords().forEach(practice -> {
            String image = practice.getPracticeImage();
            if (StringUtils.isNotBlank(image)) {
                // 去除扩展名并生成完整的图片URL
                String fileWithoutExtension = image.contains(".") ? image.substring(0, image.lastIndexOf('.')) : image;
                String projectImageUrl = ossService.getStudyTreeResourceUrl("dataset-square-migrate", "study_practice/" + fileWithoutExtension);
                practice.setPracticeImage(projectImageUrl); // 设置返回的URL
            }
        });

        return resultPage;
    }

    public List<StudyPracticeBook> getPracticeBookByPracticeId(Long practiceId) {
        LambdaQueryWrapper<StudyPracticeBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudyPracticeBook::getPracticeId, practiceId);

        List<StudyPracticeBook> practiceBooks = studyPracticeBookMapper.selectList(queryWrapper);

        // 对每个 StudyPracticeBook 对象的 content 进行处理
        for (StudyPracticeBook book : practiceBooks) {
            String originalContent = book.getContent();
            if (originalContent != null && !originalContent.isEmpty()) {
                String updatedContent = updateOssLinks(originalContent);
                book.setContent(updatedContent);
            }
        }

        return practiceBooks;
    }

    private String updateOssLinks(String noteContent) {
        if (noteContent == null || noteContent.isEmpty()) {
            return noteContent;
        }

        // 使用正则表达式匹配所有 OSS 链接
        String ossUrlPattern = "http[s]?://[a-zA-Z0-9-.]+/([a-zA-Z0-9/_%-]+\\.[a-zA-Z]+)(\\?[^\"\\s]*)?";
        Pattern pattern = Pattern.compile(ossUrlPattern);
        Matcher matcher = pattern.matcher(noteContent);

        StringBuffer updatedContent = new StringBuffer();

        while (matcher.find()) {
            String originalUrl = matcher.group(0); // 原始链接
            String objectKey = matcher.group(1); // OSS 对象存储的路径
            System.out.println(objectKey);
            // 获取新的签名 URL
            String newUrl = ossService.getFileUrl(objectKey);
            if (newUrl == null) {
                log.warn("无法生成新签名URL，保留原始链接：" + originalUrl);
                newUrl = originalUrl; // 如果生成失败，保留原始链接
            }
            // 替换旧链接为新链接
            matcher.appendReplacement(updatedContent, newUrl);
        }

        matcher.appendTail(updatedContent);

        return updatedContent.toString();
    }
}
